package demo2;

import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }
    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    /**
     * 向下调整建堆的时间复杂度 : O(n)
     * @param parent
     * @param len
     */
    public void shiftDown (int parent, int len) {
        int child = parent * 2 + 1;
        while (child < len) {
            if ((child + 1) < len && (elem[child] < elem[child+1])) {
                child++;
            }
            if (elem[parent] < elem[child]) {
                int temp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = temp;
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    /**
     * 向上调整建堆的时间复杂度 : O(n * logn)
     * @param child
     */
    public void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                int temp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = temp;
                child = parent;
                parent = (parent - 1) / 2;
            } else {
                break;
            }
        }
    }
    public void createHeap(int[] array) {
        initElem(array);
        for (int i = 0; i < array.length; i++) {
            shiftUp(i);
        }
    }
    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }
    public void offer (int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem,this.elem.length * 2);
        }
        elem[usedSize++] = val;
        //向上调整
        shiftUp(--usedSize);
    }
    public boolean isFull() {
        return usedSize == elem.length;
    }
    public void pop() {
        if (isEmpty()) return;
        elem[0] = elem[--usedSize];
        shiftDown(0,usedSize);
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }
}
